package juc.utils.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author 夏焰波
 * @date 2020-06-25 17:08
 */
public class SemaphoreExample1 {
    public static void main(String[] args) {
        final SemaphoreLock lock = new SemaphoreLock();
        for (int i = 0; i < 2; i++) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + " is running");

                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + " get the #SemaphoreLock");
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                    System.out.println(Thread.currentThread().getName() + " released #SemaphoreLock");

                }
            }.start();
        }
    }

    static class SemaphoreLock {
        private final Semaphore semaphore = new Semaphore(1);

        public void lock() throws InterruptedException {
            semaphore.acquire();//计数，相当于拿许可证(令牌)，取不到会被block
        }

        public void unlock() {
            semaphore.release();
        }
    }
}
